package com.itheima.auth.handle;

import com.itheima.utils.JwtTokenUtil;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登入ajax请求成功后的处理器
 * */
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        //登入账户信息
        String username = ((UserDetails) authentication.getPrincipal()).getUsername();
        //生成token
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("flag",true);
            jsonObject.put("data", JwtTokenUtil.createToken(username));
            jsonObject.put("message","");
            response.getWriter().write(jsonObject.toString());
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write(e.getMessage());
        }
    }

}
